<template>
  <div>
    <div>
      <el-container>
        <el-main>
          <el-header class="header-class" height="22">
            <div class="header-text">Temp User Maintenance</div>
          </el-header>
          <div class="panel-border">
            <div class="search-panel">
              <el-form label-position="left">
                <el-form-item label="Domain ID:" label-width="130px" class="search-form-item">
                  <el-col :span="8">
                    <el-input :size="'mini'" v-model="domainIdCondition"></el-input>
                  </el-col>
                </el-form-item>
                <el-form-item label="Department:" label-width="130px" class="search-form-item">
                  <el-col :span="8">
                    <el-select v-model="departmentCondition" placeholder="Select" :size="'mini'">
                      <el-option
                        v-for="item in departments"
                        :key="item"
                        :label="item"
                        :value="item">
                      </el-option>
                    </el-select>
                  </el-col>
                </el-form-item>
              </el-form>
            </div>
            <el-row>
              <div class="add-button-class">
                <el-button @click="onAddTempUser">Add Temp User</el-button>
              </div>
            </el-row>
            <el-table ref="table" border class="table" :data="tableData" style="width: 98%">
              <el-table-column label="#" width="50">
                <template slot-scope="scope">
                  {{(currentPage-1) * limit + scope.$index + 1}}
                </template>
              </el-table-column>
              <el-table-column label="Department" prop="department">
              </el-table-column>
              <el-table-column label="Domain ID" prop="domainId">
              </el-table-column>
              <el-table-column label="Email" prop="email">
              </el-table-column>
              <el-table-column label="Country" prop="country">
              </el-table-column>
              <el-table-column label="Address" prop="address">
              </el-table-column>
              <el-table-column label="Display Name" prop="displayName">
              </el-table-column>
              <el-table-column label="Created AT" prop="createdAt">
              </el-table-column>
              <el-table-column label="Last Updated AT" prop="updatedAt">
              </el-table-column>
              <el-table-column label="Action">
                <template slot-scope="scope">
                  <el-button size="mini" @click="handleEdit(scope.$index, scope.row)" icon="el-icon-edit">Edit
                  </el-button>
                  <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)" icon="el-icon-delete">Delete
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-container>
              <div class="pagination">
                <el-pagination layout="prev, pager, next" :total="totalElements" :page-size="limit"
                               @current-change="onPageChange">
                </el-pagination>
              </div>
            </el-container>
          </div>
          <el-dialog
            class="dialog"
            title="Temp User"
            :center="true"
            :show-close="false"
            :top="'15px'"
            :visible.sync="dialogVisible"
            width="30%">
            <temp-user-list-maintenance-edit-form ref="editForm"></temp-user-list-maintenance-edit-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="onCancel">Cancel</el-button>
              <el-button type="primary" @click="onConfirm">Confirm</el-button>
            </span>
          </el-dialog>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script>
import tempUserService from '@/service/user'
import TempUserListMaintenanceEditForm from './TempUserListMaintenanceEditForm'
import ElForm from 'element-ui/packages/form/src/form'
import _ from 'lodash'
import util from '@/common/js/util'

let tempUserSearchFilter = {
  fieldName: 'needSync',
  operator: 'EQ',
  value: false
}

export default {
  components: {
    ElForm,
    TempUserListMaintenanceEditForm
  },
  mounted() {
    this.getTempUsers(1)
    this.getTempUsersDepartments()
  },
  data() {
    return {
      currentPage: 1,
      dialogVisible: false,
      isNewDataFlag: false,
      tableData: [],
      totalElements: 0,
      limit: 10,
      departments: [],
      domainIdCondition: '',
      departmentCondition: ''
    }
  },
  watch: {
    domainIdCondition: 'queryUser',
    departmentCondition: 'queryUser'
  },
  methods: {
    searchWithSearchCondition: _.debounce((me) => {
      me.getTempUsers(1, me.getFilterCondition())
    }, 2000),
    getFilterCondition() {
      let searchFilterList = []
      if (this.domainIdCondition) {
        let domainIdSearchFilter = {
          fieldName: 'domainId',
          operator: 'LIKE',
          value: this.domainIdCondition
        }
        searchFilterList.push(domainIdSearchFilter)
      }
      if (this.departmentCondition) {
        let departmentSearchFilter = {
          fieldName: 'department',
          operator: 'EQ',
          value: this.departmentCondition
        }
        searchFilterList.push(departmentSearchFilter)
      }
      return searchFilterList
    },
    queryUser() {
      this.searchWithSearchCondition(this)
    },
    handleEdit(index, row) {
      this.dialogVisible = true
      let tempObject = util.deepClone(row)
      this.$nextTick(() => {
        this.$refs['editForm'].setFormModel(tempObject)
      })
    },
    handleDelete(index, row) {
      this.deleteTempUser(row.staffId)
    },
    onAddTempUser() {
      let newData = {
        active: 1,
        address: null,
        country: null,
        createdAt: null,
        department: null,
        displayName: null,
        domainId: null,
        email: null,
        fax: null,
        firstName: null,
        gender: null,
        jobTitle: null,
        lastName: null,
        location: null,
        middleName: null,
        needSync: false,
        office: null,
        officeCode: null,
        phone: null,
        section1: null,
        section2: null,
        staffId: null,
        updatedAt: null
      }
      this.isNewDataFlag = true
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['editForm'].setFormModel(newData)
      })
    },
    onConfirm() {
      let userData = this.$refs['editForm'].getFormModel()
      userData.domainId = userData.domainId.toUpperCase()
      if (!userData.staffId) {
        userData.staffId = userData.domainId
      }
      let me = this
      this.$refs['editForm'].validateForm().then(async (valid) => {
        if (valid) {
          await me.addTempUser(userData)
        }
      })
    },
    onCancel() {
      this.dialogVisible = false
    },
    onPageChange(page) {
      this.getTempUsers(page, this.getFilterCondition())
    },
    async getTempUsers(pageNumber, searchFilters) {
      this.currentPage = pageNumber
      let queryCondition = {
        searchFilters: [tempUserSearchFilter],
        page: pageNumber,
        start: 0,
        limit: this.limit
      }
      if (searchFilters !== undefined) {
        queryCondition.searchFilters = queryCondition.searchFilters.concat(searchFilters)
      }
      let tempUserList = await tempUserService.getTempUserWithConditionResult(queryCondition)
      this.tableData = tempUserList.content
      this.totalElements = tempUserList.totalElements
    },
    async addTempUser(userData) {
      this.dialogVisible = false
      await tempUserService.addTempUserResult(userData)
      this.getTempUsers(1, this.getFilterCondition())
    },
    async deleteTempUser(id) {
      this.dialogVisible = false
      await tempUserService.deleteTempUserResult(id).then((result) => {
        if (result.status >= 400) {
          this.$message({
            showClose: true,
            message: 'This user is a team endorser. Please remove from team endorser list first',
            type: 'error'
          })
        }
      })
      this.getTempUsers(1, this.getFilterCondition())
    },
    async getTempUsersDepartments() {
      let departments = await tempUserService.getTempUserDepartmentsResult()
      let result = [''].concat(departments)
      this.departments = result
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../common/css/base.scss';

  .add-button-class {
    margin-left: 15px;
  }

  .pagination {
    align-items: center;
    margin-left: auto;
    margin-right: auto;
  }

  .panel-border {
    border: 1px solid $base-header-color;
  }

  .search-panel {
    height: 100px;
    margin: 10px;
    padding: 10px;
    border: 1px solid $base-header-color;
  }

  .table {
    margin: 15px;
  }

  .header-class {
    @include baseHeader(30px);
  }

  .header-text {
    color: #fff;
    padding-top: 5px;
    font-weight: bold;
  }

  .el-form-item.search-form-item {
    margin-bottom: 0px;
  }

</style>
